package com.mediacloud.app.newsmodule.view

import android.Manifest
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.PixelFormat
import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.text.SpannableString
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.util.TypedValue
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.CheckBox
import android.widget.CompoundButton
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.launcher.ARouter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chinamcloud.asr.AsrEventListener
import com.chinamcloud.asr.IAsrCommentProvider
import com.chinamcloud.collect.AcquisitionManager
import com.eventTrack.CDPTrackReportManager
import com.eventTrack.TXReportManager
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.mediacloud.app.asr.BsgDownload.Companion.SavePath
import com.mediacloud.app.assembly.util.isFastClick
import com.mediacloud.app.model.CommentCommitEvent
import com.mediacloud.app.model.CommentCommitPushEvent
import com.mediacloud.app.model.CommentDismissEvent
import com.mediacloud.app.model.fragment.BaseFragment
import com.mediacloud.app.model.interfaces.DataInvokeCallBack
import com.mediacloud.app.model.interfaces.ICommentObj
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.BaseMessageReciver
import com.mediacloud.app.model.utils.ViewUtils
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.fragment.NotifyMicroEvent
import com.mediacloud.app.newsmodule.model.NewsCommentItem
import com.mediacloud.app.newsmodule.model.ReplyCommentItem
import com.mediacloud.app.newsmodule.model.ReplyListHelper
import com.mediacloud.app.newsmodule.utils.Addintegral
import com.mediacloud.app.newsmodule.utils.AppPermissionUtils
import com.mediacloud.app.newsmodule.utils.CommentPublishInvoker
import com.mediacloud.app.newsmodule.utils.DomainUtil
import com.mediacloud.app.newsmodule.utils.LoginUtils
import com.mediacloud.app.newsmodule.utils.ReplyCommentInvoker
import com.mediacloud.app.newsmodule.utils.ToastUtil
import com.mediacloud.app.newsmodule.view.adapter.EmojiAdapter
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig
import com.mediacloud.app.reslib.enums.XKey
import com.mediacloud.app.reslib.view.SimpleDialog
import com.mediacloud.app.user.model.UserInfo
import com.tencent.mmkv.MMKV
import com.utils.*
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import org.greenrobot.eventbus.EventBus
import org.jetbrains.anko.backgroundColor
import org.json.JSONException
import org.json.JSONObject

class CommentDialog : AppCompatActivity(), View.OnClickListener, AsrEventListener,
    View.OnLongClickListener {

    companion object {
        var saveArticleId: Long? = null
        var saveType: Int? = null
        var saveText: Editable? = null
        var path:String?=null
        private fun checkPath(context: Context) {
            if (!TextUtils.isEmpty(path)&& !path!!.equals(context.toString())){
                clearSaveData()
            }
            path=context.toString()
        }
        private fun clearSaveData(){
            saveArticleId=null
            saveType=null
            saveText=null
        }
        fun startActivity(
            context: Context?,
            articleItem: ArticleItem?,
            isFace: Boolean,
            isMicroLive: Boolean = false
        ) {
            if (context == null) {
                return
            }
            checkPath(context)
            val intent = Intent(context, CommentDialog::class.java)
            intent.putExtra("data", articleItem)
            intent.putExtra("isFace", isFace)
            intent.putExtra("isMicroLive", isMicroLive)
            context.startActivity(intent)
        }
        fun startActivity(
            context: Context?,
            articleItem: ArticleItem?,
            isFace: Boolean,
            isMicroLive: Boolean = false,
            isLive: Boolean = false
        ) {
            if (context == null) {
                return
            }
            checkPath(context)
            val intent = Intent(context, CommentDialog::class.java)
            intent.putExtra("data", articleItem)
            intent.putExtra("isFace", isFace)
            intent.putExtra("isMicroLive", isMicroLive)
            intent.putExtra("isLive", isLive)
            context.startActivity(intent)
        }

        fun startActivity(
            context: Context?, articleItem: ArticleItem?, isFace: Boolean, type: Int
        ) {
            if (context == null) {
                return
            }
            checkPath(context)
            val intent = Intent(context, CommentDialog::class.java)
            intent.putExtra("isFace", isFace)
            intent.putExtra("type", type)
            intent.putExtra("data", articleItem)
            context.startActivity(intent)
        }

        fun startActivity(
            context: Context?, articleItem: ArticleItem?, isReply: Boolean, item: NewsCommentItem
        ) {
            if (context == null) {
                return
            }
            checkPath(context)
            val intent = Intent(context, CommentDialog::class.java)
            intent.putExtra("isReply", isReply)
            intent.putExtra("news_item", item)
            intent.putExtra("data", articleItem)
            context.startActivity(intent)
        }

        fun startActivity(
            context: Context?, articleItem: ArticleItem?, isReply: Boolean, item: ReplyCommentItem
        ) {
            if (context == null) {
                return
            }
            checkPath(context)
            val intent = Intent(context, CommentDialog::class.java)
            intent.putExtra("isReply", isReply)
            intent.putExtra("reply_item", item)
            intent.putExtra("data", articleItem)
            context.startActivity(intent)
        }

        fun startActivity(
            context: Context?,
            articleItem: ArticleItem?,
            type: Int,
            access_token: String,
            isSpider: Boolean
        ) {
            if (context == null) {
                return
            }
            checkPath(context)
            val intent = Intent(context, CommentDialog::class.java)
            intent.putExtra("type", type)
            intent.putExtra("isSpider", isSpider)
            intent.putExtra("access_token", access_token)
            intent.putExtra("data", articleItem)
            context.startActivity(intent)
        }

        fun startActivity(
            context: Context?,
            articleItem: ArticleItem?,
            type: Int,
            access_token: String,
            isSpider: Boolean,
            isFace: Int
        ) {
            if (context == null) {
                return
            }
            checkPath(context)
            val intent = Intent(context, CommentDialog::class.java)
            intent.putExtra("type", type)
            intent.putExtra("isSpider", isSpider)
            intent.putExtra("access_token", access_token)
            intent.putExtra("isFace", isFace == 1)
            intent.putExtra("data", articleItem)
            context.startActivity(intent)
        }

        fun startActivity(
            context: Context?,
            articleItem: ArticleItem?,
            type: Int,
            access_token: String,
            isSpider: Boolean,
            isReply: Boolean
        ) {
            if (context == null) {
                return
            }
            checkPath(context)
            val intent = Intent(context, CommentDialog::class.java)
            intent.putExtra("type", type)
            intent.putExtra("isSpider", isSpider)
            intent.putExtra("access_token", access_token)
            intent.putExtra("isReply", isReply)
            intent.putExtra("data", articleItem)
            context.startActivity(intent)
        }

        fun startActivity(
            context: Context?,
            articleItem: ArticleItem?,
            type: Int,
            isSpider: Boolean,
            isReply: Boolean
        ) {
            if (context == null) {
                return
            }
            checkPath(context)
            val intent = Intent(context, CommentDialog::class.java)
            intent.putExtra("type", type)
            intent.putExtra("isSpider", isSpider)
            intent.putExtra("isReply", isReply)
            intent.putExtra("data", articleItem)
            context.startActivity(intent)
        }


        fun startActivity(
            context: Context?,
            articleItem: ArticleItem?,
            type: Int,
            access_token: String,
            isSpider: Boolean,
            isReply: Boolean,
            item: NewsCommentItem
        ) {
            if (context == null) {
                return
            }
            checkPath(context)
            val intent = Intent(context, CommentDialog::class.java)
            intent.putExtra("type", type)
            intent.putExtra("isSpider", isSpider)
            intent.putExtra("access_token", access_token)
            intent.putExtra("isReply", isReply)
            intent.putExtra("news_item", item)
            intent.putExtra("data", articleItem)
            context.startActivity(intent)
        }

        fun startActivity(
            context: Context?,
            articleItem: ArticleItem?,
            type: Int,
            access_token: String,
            isSpider: Boolean,
            isReply: Boolean,
            item: ReplyCommentItem
        ) {
            if (context == null) {
                return
            }
            checkPath(context)
            val intent = Intent(context, CommentDialog::class.java)
            intent.putExtra("type", type)
            intent.putExtra("isSpider", isSpider)
            intent.putExtra("isReply", isReply)
            intent.putExtra("reply_item", item)
            intent.putExtra("access_token", access_token)
            intent.putExtra("data", articleItem)
            context.startActivity(intent)
        }
    }

    var writeComment: TextView? = null
    var tv_num: TextView? = null
    var commentInputText: EditText? = null
    var articleItem: ICommentObj? = null
    private var mReplyCommentInvoker: ReplyCommentInvoker? = null
    private var commentPublishInvoker: CommentPublishInvoker? = null
    private var callBack: SubmitCommentCallBack? = null
    private var simpleDialog: SimpleDialog? = null
    private val VIEW_LOG_TAG = "test"
    private var copyandpaste: View? = null
    private var mClipboard: ClipboardManager? = null
    var isReply = false
    var isLive = false

    // var isSpider = false
    var isFace = false
    var isMicroLive = false
    var access_token: String? = null
    private var comment_id: Long = 0
    private var reply_avatar: String? = null
    private var reply_nickname = ""
    private var reply_uid = ""
    private var anonymousCheckBox: CheckBox? = null
    private var anonymous = 0
    var type = 1


    private var ivEmoji //军号表情Emoji
            : ImageView? = null
    private var rcyEmoji: RecyclerView? = null
    private val emojiAdapter: EmojiAdapter? = null
    private var isShowEmoji = false


    var statusText: TextView? = null
    var inputModeImg: ImageView? = null
    var voiceInputLayout: View? = null
    var voiceInputBtn: ImageView? = null
    private var mChange: CheckBox? = null
    private var mMemes: LinearLayout? = null
    private var viewBg: LinearLayout? = null
    private var mTl: TabLayout? = null
    private var mVp: ViewPager2? = null
    private var topContent: RelativeLayout? = null
    private var mTvMaxnum: TextView? = null
    private var asrCommentProvider: IAsrCommentProvider? = null
    private var imm: InputMethodManager? = null
    var isIm = false
    var keyBoarFlag = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

//        setTheme(R.style.TranslucentTheme)
        overridePendingTransition(0, R.anim.base_activity_bottom_out)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            window.decorView.systemUiVisibility =
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window.statusBarColor = 0
        }
        setContentView(R.layout.activity_layout_comment)
        if (MMKV.defaultMMKV().getBoolean(XKey.DARK_MODE, false)) {
            var dialogDarkMask =
                layoutInflater.inflate(com.mediacloud.app.reslib.R.layout.mask_darkmode, null)
            if (MMKV.defaultMMKV().getBoolean(XKey.DARK_MODE, false)) {
                val lp = WindowManager.LayoutParams(
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.TYPE_APPLICATION,
                    WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                    PixelFormat.TRANSLUCENT
                )
                addContentView(dialogDarkMask, lp)
            }
            window.navigationBarColor = getColor(R.color.navigation_dark_mode)
        }
        articleItem = intent.getParcelableExtra<ArticleItem>("data")
        var news_item = intent.getParcelableExtra<NewsCommentItem>("news_item")
        var reply_item = intent.getParcelableExtra<NewsCommentItem>("reply_item")
        type = intent.getIntExtra("type", 1)
        isFace = intent.getBooleanExtra("isFace", false)
        isLive = intent.getBooleanExtra("isLive", false)
        isMicroLive = intent.getBooleanExtra("isMicroLive", false)
        //   isSpider = intent.getBooleanExtra("isSpider", false)
        isReply = intent.getBooleanExtra("isReply", false)
        access_token = intent.getStringExtra("access_token")
        initView()
        var provider = SoftKeyboardHeightProvider(this)
        provider.init()
        provider.listener = object : SoftKeyboardHeightProvider.KeyboardListener {
            @SuppressLint("ObjectAnimatorBinding")
            override fun onHeightChanged(heigt: Int) {
                // 键盘高度变化
                if (heigt > 0) {
                    if (!keyBoarFlag) {
                        val animator =
                            ObjectAnimator.ofFloat(topContent, "translationY", heigt.toFloat(), 0f)
                        animator.duration = 100
                        animator.start()
                        topContent?.visibility = View.VISIBLE
                        keyBoarFlag = true
                    }
                    val layoutParams = mMemes!!.layoutParams as RelativeLayout.LayoutParams
                    layoutParams.height = heigt
                    mMemes!!.layoutParams = layoutParams
                }else{
                    val layoutParams = mMemes!!.layoutParams as RelativeLayout.LayoutParams
                    layoutParams.height = 0
                    mMemes!!.layoutParams = layoutParams
                }
            }
        }
        if (news_item != null) {
            setReplyData(news_item)
        }
        if (reply_item != null) {
            setReplyData(reply_item)
        }
        if (TextUtils.isEmpty(reply_nickname)) {
            commentInputText?.hint = "我来说几句"
        } else {
            commentInputText?.hint = "回复@" + reply_nickname
        }
        mChange?.isChecked = isFace
//        if (isFace) {
//            topContent?.visibility = View.VISIBLE
//            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
//        } else {
//            topContent?.visibility = View.VISIBLE
////            commentInputText?.isFocusable = true
////            commentInputText?.isFocusableInTouchMode = true
////            commentInputText?.requestFocus()
////            commentInputText?.findFocus()
////            val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
////            imm.showSoftInput(commentInputText, 0)
//            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
//
//        }
        checkSaveData()

        if(isLive){
            mTvMaxnum?.text = "50"
        }else{
            mTvMaxnum?.text = "500"
        }
        commentInputText?.requestFocus()
        imm?.showSoftInput(commentInputText, InputMethodManager.SHOW_IMPLICIT)
    }

    private fun initView() {

        asrCommentProvider = ARouter.getInstance().navigation(IAsrCommentProvider::class.java)
        if (asrCommentProvider != null) {
            asrCommentProvider?.init(this, this)
        }

        voiceInputBtn = findViewById(R.id.voiceInputBtn)
        mTvMaxnum = findViewById(R.id.tv_maxnum)
        inputModeImg = findViewById(R.id.inputModeImg)
        ivEmoji = findViewById(R.id.ivEmoji)
        rcyEmoji = findViewById(R.id.rcyEmoji)
        commentInputText = findViewById(R.id.commentInputText)
        topContent = findViewById(R.id.topContent)
        viewBg = findViewById(R.id.view_bg)
        imm = this.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        viewBg!!.setOnClickListener { v: View? -> finish() }
        findViewById<View>(R.id.commentInputSend).setOnClickListener { v: View? -> }
        if (AppFactoryGlobalConfig.getAppServerConfigInfo(this).otherFunction != null && AppFactoryGlobalConfig.getAppServerConfigInfo(
                this
            ).otherFunction.voice_comment == 1
        ) {
            inputModeImg?.visibility = View.VISIBLE
            if (asrCommentProvider == null) {
                inputModeImg?.visibility = View.GONE
            }
        } else {
            mChange = findViewById(R.id.comment_memes_keyboard)
            mMemes = findViewById(R.id.comment_memes)
            mTl = findViewById(R.id.comment_memes_tl)
            mVp = findViewById(R.id.comment_memes_vp)
//            inputModeImg?.visibility = View.GONE
//            ivEmoji?.visibility = View.GONE
//            mVp?.adapter = object : FragmentStateAdapter(supportFragmentManager, lifecycle) {
//                override fun createFragment(position: Int): Fragment {
//                    val emojiIdList: MutableList<String> = ArrayList()
//                    val urlList: MutableList<String> = ArrayList()
//                    var emoji: List<String>
//                    if (mEmojiMap.isNotEmpty()) {
//                        emoji = mEmojiMap[mTabTitleList[position]]!!
//                    } else {
//                        //防止没拿到表情，再取一次
//                        startEmoji(this@CommentDialog)
//                        emoji = mEmojiMap[mTabTitleList[position]]!!
//                    }
//                    for (j in emoji.indices) {
//                        val s = emoji[j]
//                        val split = s.split(",").toTypedArray()
//                        emojiIdList.add(split[0])
//                        urlList.add(split[1])
//                    }
//                    val memesFragment = MemesFragment()
//                    memesFragment.editText = commentInputText!!
//                    memesFragment.idList = emojiIdList
//                    memesFragment.urlList = urlList
//                    return memesFragment
//                }
//
//                override fun getItemCount(): Int {
//                    return mTabTitleList.size
//                }
//            }
//            TabLayoutMediator(mTl!!,
//                mVp!!,
//                TabLayoutMediator.TabConfigurationStrategy { tab: TabLayout.Tab, position: Int ->
//                    tab.text = mTabTitleList[position]
//                }).attach()
//            commentInputText?.setOnTouchListener(View.OnTouchListener { v: View?, event: MotionEvent ->
//                if (event.action == MotionEvent.ACTION_DOWN) {
//                    commentInputText?.isFocusable = true
//                    commentInputText?.isFocusableInTouchMode = true
//                    commentInputText?.requestFocus()
//                    commentInputText?.findFocus()
//                    mChange?.isChecked = false
//                }
//                false
//            })
//            mChange?.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { compoundButton: CompoundButton, b: Boolean ->
//                if (compoundButton.isChecked) {
//                    val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
//                    imm.hideSoftInputFromWindow(commentInputText?.windowToken, 0)
//
//                } else {
//                    commentInputText?.isFocusable = true
//                    commentInputText?.isFocusableInTouchMode = true
//                    commentInputText?.requestFocus()
//                    commentInputText?.findFocus()
//                    val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
//                    imm.showSoftInput(commentInputText, 0)
//                }
//                keyBoarFlag = true
//            })
        }
        voiceInputLayout = findViewById(R.id.voiceInputLayout)
        statusText = findViewById(R.id.statusText)

        commentInputText?.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence, p1: Int, p2: Int, p3: Int) {
                if(isLive){
                    if (p0.isNotEmpty() && p0.length <= 50) {
                        writeComment?.isEnabled = true
                        writeComment?.alpha = 1f
                        tv_num?.setTextColor(getColor(R.color._999))
                    } else {
                        if (p0.isNotEmpty() && p0.length > 50) {
                            tv_num?.setTextColor(getColor(R.color.color_e41d1d))
                        } else {
                            tv_num?.setTextColor(getColor(R.color._999))
                        }
                        writeComment?.isEnabled = false
                        writeComment?.alpha = 0.5f
                    }
                }else{
                    if (p0.isNotEmpty() && p0.length <= 500) {
                        writeComment?.isEnabled = true
                        writeComment?.alpha = 1f
                        tv_num?.setTextColor(getColor(R.color._999))
                    } else {
                        if (p0.isNotEmpty() && p0.length > 500) {
                            tv_num?.setTextColor(getColor(R.color.color_e41d1d))
                        } else {
                            tv_num?.setTextColor(getColor(R.color._999))
                        }
                        writeComment?.isEnabled = false
                        writeComment?.alpha = 0.5f
                    }
                }
                tv_num?.text = p0.length.toString() + "/"
            }

            override fun afterTextChanged(p0: Editable?) {

            }

        })
        setAnonymousView()
        initChild()
        initDataInvoker()
        commentInputText?.setOnLongClickListener(this)
        mClipboard = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
        inputModeImg?.setOnClickListener(View.OnClickListener { v: View? ->
            if (inputModeImg?.tag == null) {
                voiceInputMode()
            } else {
                keyInputMode()
            }
        })
        voiceInputBtn!!.setOnClickListener(View.OnClickListener { v: View? ->
            if (status != Status.PROCESSING) {
                val permissions = arrayOf(Manifest.permission.RECORD_AUDIO)
                AppPermissionUtils.doAuthPermissionCall(
                    ViewUtils.searchTintContextHostActivity(
                        this
                    ), { aBoolean: Boolean ->
                        if (aBoolean) {
                            start()
                            voiceInputBtn!!.setImageResource(R.drawable.vocie_input_complete)
                            status = Status.PROCESSING
                        }
                    }, permissions, true
                )
            } else {
                stop()
                voiceInputBtn!!.setImageResource(R.drawable.voice_helper_microphone)
            }
        })


    }

    private fun initDataInvoker() {
        val mReplyCommentCallBack: ReplyCommentCallBack = ReplyCommentCallBack()
        mReplyCommentInvoker = ReplyCommentInvoker(mReplyCommentCallBack)
    }

    var ss: SpannableString? = null
    private fun pasteToResult() {
        var resultString: String? = ""
        // 检查剪贴板是否有内容
        if (mClipboard!!.hasPrimaryClip()) {
            val clipData = mClipboard!!.primaryClip
            val count = clipData!!.itemCount
            for (i in 0 until count) {
                val item = clipData.getItemAt(i)
                val str = item.coerceToText(this)
                Log.i("mengdd", "item : $i: $str")
                resultString += str
            }
        }
        commentInputText!!.append(
            decodeFaceFormStr(
                resultString!!, commentInputText!!.context
            )
        )
        commentInputText!!.setSelection(commentInputText!!.text.length)
    }

    //是否开启匿名回复
    fun setAnonymousView() {
        anonymousCheckBox = findViewById<CheckBox>(R.id.anonymousCheckBox)
        if ( /*this.getResources().getString(R.string.needAnonymous).equals("0")*/AppFactoryGlobalConfig.getAppServerConfigInfo(
                this
            ).otherFunction != null && AppFactoryGlobalConfig.getAppServerConfigInfo(this).otherFunction.anonymous_comment <= 0 /*|| isSpider*/) anonymousCheckBox?.visibility =
            View.GONE
        anonymousCheckBox?.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { compoundButton: CompoundButton, b: Boolean ->
            if (compoundButton.isChecked) {
                anonymousCheckBox?.setTextColor(resources.getColor(R.color.style_blue))
                anonymous = 1
            } else {
                anonymous = 0
                anonymousCheckBox?.setTextColor(resources.getColor(R.color.color_333333))
            }
        })
    }

    protected fun initChild() {
        simpleDialog = SimpleDialog(this)
        callBack = SubmitCommentCallBack()
        commentPublishInvoker = CommentPublishInvoker(callBack)
        copyandpaste = findViewById<View>(R.id.copyandpaste)
        copyandpaste?.setOnClickListener(this)
        writeComment = findViewById<TextView>(R.id.write_comment)
        tv_num = findViewById<TextView>(R.id.tv_num)

        /*StateListDrawable drawable = (StateListDrawable) writeComment.getBackground();
        GradientDrawable drawable1 = (GradientDrawable) drawable.getStateDrawable(1);
        drawable1.setColor(DefaultBgUtil.getTintColor(this));*/
        // writeComment.setBackground(drawable);
        val size = resources.getDimensionPixelSize(R.dimen.dimen_16sp).toFloat()
        commentInputText?.setTextSize(TypedValue.COMPLEX_UNIT_PX, size)

        commentInputText?.setOnClickListener { keyInputMode() }
        writeComment!!.setOnClickListener(this)
    }

    fun voiceInputMode() {
        val inputmanger = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        inputmanger.hideSoftInputFromWindow(
            commentInputText?.windowToken, 0
        )
        inputModeImg!!.setImageResource(R.drawable.input_mode_keyborad)
        inputModeImg!!.tag = 1
        voiceInputLayout!!.postDelayed({ voiceInputLayout!!.visibility = View.VISIBLE }, 300)
    }

    fun keyInputMode() {
        hideEmoji()
        inputModeImg!!.tag = null
        inputModeImg!!.setImageResource(R.drawable.icon_voice_input)
        voiceInputLayout!!.postDelayed({
            val inputmanger = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            inputmanger.showSoftInput(commentInputText, 0)
        }, 300)
        voiceInputLayout!!.visibility = View.GONE
    }


    /**
     * 提交评论的回调
     */
    inner class SubmitCommentCallBack : DataInvokeCallBack<BaseMessageReciver> {
        override fun success(data: BaseMessageReciver) {
            if (isFinishing || isDestroyed) {
                return
            }
            if (data.state) {
                //评论数据采集
                val info = UserInfo.getUserInfo(this@CommentDialog)
                val comment: String = commentInputText?.text.toString()
                val p = AcquisitionManager.getInstance()
                if (articleItem != null) {
                    p.comment(
                        info,
                        articleItem!!.id.toString() + "",
                        DomainUtil.getDomain(articleItem!!.url),
                        articleItem!!.url,
                        articleItem!!.title,
                        articleItem!!.content,
                        comment
                    )
                }
                EventBus.getDefault()
                    .post(CommentCommitPushEvent(comment, reply_nickname, reply_uid))
                commentInputText?.text?.clear()
                clearSaveData()
                if (articleItem is ArticleItem) {
                    TXReportManager.getInstance().app_jhapp_content_detail_interact(
                        "评论", "", "", articleItem as ArticleItem
                    );
                    CDPTrackReportManager.getInstance().comment(articleItem as ArticleItem,comment)
                } else {
                    TXReportManager.getInstance()
                        .app_jhapp_content_detail_interact("评论", "", "", null);
                }

                var isStudy = "0"
                if (articleItem is ArticleItem) {
                    if ((articleItem as ArticleItem).movie != null && (articleItem as ArticleItem).movie.isStudyContent != null) {
                        isStudy =
                            if ("1" == (articleItem as ArticleItem).movie.isStudyContent) "1" else "0"
                    }
                }
                if (articleItem != null) {
                    if (articleItem is ArticleItem) {
                        Addintegral.addintegral(
                            this@CommentDialog,
                            articleItem!!.id,
                            3,
                            isStudy,
                            articleItem as ArticleItem
                        )
                    } else {
                        Addintegral.addintegral(
                            this@CommentDialog, articleItem!!.id, 3, isStudy, null
                        )
                    }
                } else {
                    Addintegral.addintegral(this@CommentDialog, 3, isStudy, null)
                }
                EventBus.getDefault().post(CommentCommitEvent(true))
                ToastUtil.showCustomView(this@CommentDialog, R.string.comment_success)
                simpleDialog?.dismiss()
                finish()
            } else {
                fault("error")
            }
            Log.w(VIEW_LOG_TAG, "success$data")

        }

        override fun fault(data: Any) {
            if (isFinishing || isDestroyed) {
                return
            }
            Log.w(VIEW_LOG_TAG, "fault$data")
            ToastUtil.showCustomView(this@CommentDialog, "该稿件不支持评论")
            EventBus.getDefault().post(CommentCommitEvent(false))
            simpleDialog?.dismiss()
//            topContent!!.visibility = View.VISIBLE
            finish()
        }
    }

    inner class ReplyCommentCallBack : DataInvokeCallBack<ReplyListHelper> {
        override fun success(data: ReplyListHelper) {
            if (isFinishing || isDestroyed) {
                return
            }
            if (data.state) {
                commentInputText?.text?.clear()
                clearSaveData()
                ToastUtil.showCustomView(this@CommentDialog, R.string.comment_success)
                var isStudy = "0"
                if (articleItem is ArticleItem && (articleItem as ArticleItem).movie != null) {
                    isStudy =
                        if ("1" == (articleItem as ArticleItem).movie.isStudyContent) "1" else "0"
                }
                if (articleItem != null) {
                    if (articleItem is ArticleItem) {
                        Addintegral.addintegral(
                            this@CommentDialog,
                            articleItem!!.id,
                            3,
                            isStudy,
                            articleItem as ArticleItem
                        )
                    } else {
                        Addintegral.addintegral(
                            this@CommentDialog, articleItem!!.id, 3, isStudy, null
                        )
                    }
                } else {
                    Addintegral.addintegral(this@CommentDialog, 3, isStudy, null)
                }
                EventBus.getDefault().post(CommentCommitEvent(true))
                simpleDialog?.dismiss()
                finish()
            } else {
                fault("error")
            }
        }

        override fun fault(data: Any) {
            if (isFinishing || isDestroyed) {
                return
            }
            ToastUtil.showCustomView(this@CommentDialog, R.string.comment_failed)
            EventBus.getDefault().post(CommentCommitEvent(false))
            simpleDialog?.dismiss()
//            topContent!!.visibility = View.VISIBLE
            finish()
        }
    }

    var status = Status.IDLE

    enum class Status {
        IDLE, PROCESSING
    }

    var recognResult = ""

    /**
     * 基于SDK集成2.2 发送开始事件
     * 点击开始按钮
     * 测试参数填在这里
     */
    @Synchronized
    private fun start() {
//        txtLog.setText("请说话 正在聆听……");
        recognResult = ""
        statusText!!.setText(R.string.is_listen_pleasesay)
        if (asrCommentProvider != null) {
            asrCommentProvider!!.start(SavePath)
        }
    }

    /**
     * 点击停止按钮
     * 基于SDK集成4.1 发送停止事件
     */
    private fun stop() {
        statusText!!.setText(R.string.comment_voiceparse)
        if (asrCommentProvider != null) {
            asrCommentProvider!!.sendStop()
        }
    }

    fun hideEmoji() {
        if (rcyEmoji != null) {
            isShowEmoji = false
            rcyEmoji!!.visibility = View.GONE
        }
    }

    /**
     * 收起软键盘，华为安全键盘弹起后会遮挡toast
     */
    fun hideInputWindow() {
        val manager = this.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager?
        manager?.hideSoftInputFromWindow(
            currentFocus!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS
        )
    }

    override fun onClick(v: View) {
        if (v.id == R.id.write_comment) {
            if (isFastClick()) publishContent()
        }

    }

    private fun publishContent() {
        val content = commentInputText?.text.toString()
        if (TextUtils.isEmpty(content.trim { it <= ' ' })) { //去空格
            ToastUtil.show(this, "请输入评论内容")
            return
        }
        val info = UserInfo.getUserInfo(this)
        if (!info.isLogin) {
            LoginUtils.request_source =LoginUtils.source_comment
            LoginUtils.invokeLogin(this@CommentDialog)
            return
        }
        if (isIm) {
//            onCommentListener?.onComment(content, reply_nickname, reply_uid)
            EventBus.getDefault().post(CommentCommitPushEvent(content, reply_nickname, reply_uid))
            return
        }
        if (isReply) {
            /*if (isSpider) submitCommunityReplay() else */submitCommentReplay()
        } else {
            if (simpleDialog?.isShowing == false && DialogUtils.canShowDialog(this)) {
                simpleDialog?.show()
                viewBg!!.backgroundColor = ContextCompat.getColor(this, R.color.transparent)
                simpleDialog?.updateText(R.string.comment_submit)
                topContent?.visibility = View.GONE

            }
//            if (isSpider) {
//                verifyTokenToLogin(articleItem?.id.toString(),content,info)
//            } else {
          //  verifyTokenToLogin(articleItem?.id.toString(), content, info)
            toCommentNext(content, info)
            //  }
        }
//        onCommentListener?.onComment(content, reply_nickname, reply_uid)
        EventBus.getDefault().post(CommentCommitPushEvent(content, reply_nickname, reply_uid))
    }

    fun toCommentNext(content: String?, userInfo: UserInfo) {
        if (isReply) {
//            if (isSpider) {
//                if (!TextUtils.isEmpty(access_token)) {
//                    commentPublishInvoker?.publishCommunityComment(
//                        articleItem!!.id.toString() + "",
//                        access_token,
//                        content?:"",
//                        "" + comment_id,
//                        reply_uid
//                    )
//                } else {
//                    getAccessToken(this@CommentDialog, userInfo, object : IAccessToken {
//                        override fun success(userInfo: UserInfo) {
//                            access_token = userInfo.access_token
//                            publishContent()
//                        }
//
//                        override fun fail() {}
//                    })
//                }
//            } else {
            mReplyCommentInvoker?.submitReplayComment(
                this@CommentDialog,
                type,
                articleItem!!.title,
                "" + articleItem!!.catalogId,
                userInfo.avatar,
                "" + comment_id,
                content ?: "",
                userInfo.nickname,
                articleItem!!.id.toString() + "",
                reply_avatar ?: "",
                userInfo.userid,
                anonymous.toString() + ""
            )
            //  }
        } else {
//            if (isSpider) {
//                if (!TextUtils.isEmpty(access_token)) {
//                    commentPublishInvoker!!.publishCommunityComment(
//                        articleItem!!.id.toString() + "",
//                        access_token,
//                        content
//                    )
//                } else {
//                    getAccessToken(this, userInfo, object : IAccessToken {
//                        override fun success(userInfo: UserInfo) {
//                            access_token = userInfo.access_token
//                            publishContent()
//                        }
//
//                        override fun fail() {}
//                    })
//                }
//            } else {
            val uid = userInfo.userid
            commentPublishInvoker?.publishComment(
                type, userInfo.avatar, userInfo.nickname, articleItem, uid, content, anonymous, this
            )
            iniAnonymousStatus()
            //  }
        }
    }

    protected fun iniAnonymousStatus() {
        anonymous = 0
        anonymousCheckBox!!.isChecked = false
    }

    //传入需要回复的评论对象
    fun setReplyData(data: NewsCommentItem) {
        comment_id = data.commentid
        reply_avatar = data.avatar
        reply_nickname = data.nickname
        reply_uid = data.uid
    }

    fun setReplyData(data: ReplyCommentItem) {
        comment_id = data.parentCid
        reply_avatar = data.avatar
        reply_nickname = data.nickName
        reply_uid = data.uid
    }

    private fun submitCommunityReplay() {

        /*  if (commentInputText.getText().length() == 0) {
            ToastUtil.show(mContext, R.string.comment_cantnull);
            return;
        }*/
        val info = UserInfo.getUserInfo(this@CommentDialog)
        if (info.isLogin) {
            if (simpleDialog?.isShowing == false && DialogUtils.canShowDialog(this)) {
                simpleDialog?.show()
                simpleDialog?.updateText(R.string.comment_submit)
                topContent!!.visibility = View.GONE

                viewBg!!.backgroundColor = ContextCompat.getColor(this, R.color.transparent)
            }
          // verifyTokenToLogin(comment_id.toString(), commentInputText?.text.toString(), info)
            toCommentNext(commentInputText?.text.toString(), info)
        } else {
            LoginUtils.request_source =LoginUtils.source_comment
            LoginUtils.invokeLogin(this@CommentDialog)
        }
    }


    private fun submitCommentReplay() {
        if (commentInputText?.text?.length == 0) {
            ToastUtil.showCustomView(this@CommentDialog, R.string.comment_cantnull)
            return
        }
        if (UserInfo.isLogin(this@CommentDialog) && DialogUtils.canShowDialog(this)) {
            simpleDialog?.show()
            simpleDialog?.updateText(R.string.comment_submit)
            topContent!!.visibility = View.GONE

            viewBg!!.backgroundColor = ContextCompat.getColor(this, R.color.transparent)
            val info = UserInfo.getUserInfo(this@CommentDialog)
           // verifyTokenToLogin(comment_id.toString(), commentInputText?.text.toString(), info)
            toCommentNext(commentInputText?.text.toString(), info)
        } else {
            LoginUtils.request_source =LoginUtils.source_comment
            LoginUtils.invokeLogin(this@CommentDialog)
        }
        iniAnonymousStatus()
    }

    protected fun verifyTokenToLogin(
        commentContentID: String?, content: String?, userInfo: UserInfo
    ) {
        WatchManManager.getCommentTokenToVerifyToken(this,
            getString(R.string.tenantid),
            commentContentID,
            content,
            object : Observer<JSONObject> {
                override fun onSubscribe(d: Disposable) {

                }

                override fun onNext(jsonObject: JSONObject) {
                    if (isFinishing || isDestroyed) {
                        return
                    }
                    //史志勇  state 非200 报这个提示
                    if (jsonObject != null && jsonObject.optInt("state", 0) == 200) {

                        toCommentNext(content, userInfo)

                    } else {
                        simpleDialog?.dismiss()
                        ToastUtil.showToastCenter(this@CommentDialog, "您的评论内容不符合规范,请重新评论")
                        finish()
                    }
                }

                override fun onError(e: Throwable) {
                    if (isFinishing || isDestroyed) {
                        return
                    }
                    simpleDialog?.dismiss()
                    ToastUtil.showToastCenter(this@CommentDialog, "网络异常，请检查网络")
                    finish()
                }

                override fun onComplete() {

                }

            })
    }

    private fun checkSaveData() {
        if (saveArticleId != null && saveType != null && saveText?.isNotEmpty() == true && articleItem?.id == saveArticleId && type == saveType) {
            commentInputText?.text = saveText
            commentInputText?.setSelection(commentInputText!!.getText().length);
        }
    }


    private fun saveData() {
        if (commentInputText?.text?.isNotEmpty() == true) {
            saveArticleId = articleItem?.id
            saveType = type
            saveText = commentInputText?.text
        }
    }

    override fun finish() {
        val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(commentInputText?.windowToken, 0)
        saveData()
        super.finish()
        EventBus.getDefault().post(CommentDismissEvent())
    }

    var lastPosition = 0
    override fun onAsrPartial(params: String?, data: ByteArray?, offset: Int, length: Int) {
        try {
            val resultJson = JSONObject(params)
            recognResult = resultJson.optString("best_result", "")
        } catch (e: JSONException) {
            e.printStackTrace()
        }

        if (params != null && params.contains("\"nlu_result\"")) {
            if (length > 0 && data!!.size > 0) {
                val result = String(data, offset, length)
                Log.w("APPTAG", "" + result)
                commentInputText?.append(result)
            }
        }
    }

    override fun onAsrExit(params: String?, data: ByteArray?, offset: Int, length: Int) {
        voiceInputBtn!!.setImageResource(R.drawable.voice_input_center)
        status = Status.IDLE
        Log.w("APPTAG", "recognResult:$recognResult")
        status = Status.IDLE
        lastPosition = 0
        if (TextUtils.isEmpty(recognResult)) {
//                ToastUtil.show(this,"没有识别出");
        } else {
            commentInputText?.append(recognResult)
        }
        statusText!!.setText(R.string.comment_voiceparse)
    }

    override fun onLongClick(p0: View?): Boolean {
//        copyandpaste!!.visibility = View.VISIBLE
        return false
    }

    //供本类中ViewPager2调用的内部公共静态Fragment类
//    internal class MemesFragment() : BaseFragment() {
//
//        var editText: EditText? = null
//        var idList: List<String>? = null//表情代号和链接地址
//        var urlList: List<String>? = null
//
//
//        private var mMemes: RecyclerView? = null
//        override fun getLayoutResID(): Int {
//            return R.layout.fragment_memes
//        }
//
//        override fun initView() {
//            mMemes = findViewById(R.id.rv_memes)
//            //删除键
//            findViewById<View>(R.id.v_memes_delete).setOnClickListener { v: View? ->
//                val keyCode = KeyEvent.KEYCODE_DEL
//                val keyEventDown = KeyEvent(KeyEvent.ACTION_DOWN, keyCode)
//                val keyEventUp = KeyEvent(KeyEvent.ACTION_UP, keyCode)
//                editText?.onKeyDown(keyCode, keyEventDown)
//                editText?.onKeyUp(keyCode, keyEventUp)
//            }
//            initEmoji()
//        }
//
//        private fun initEmoji() {
//            val emojiAdapter = EmojiAdapter(requireContext())
//            val footer = View(context)
//            val lp = ViewGroup.LayoutParams(
//                -1, requireContext().resources.getDimensionPixelSize(R.dimen.dimen34)
//            )
//            footer.layoutParams = lp
//            footer.setBackgroundColor(Color.WHITE)
//            emojiAdapter.addFooterView(footer)
//            mMemes!!.layoutManager = GridLayoutManager(context, 5)
//            mMemes!!.adapter = emojiAdapter
//            mMemes!!.layoutParams.height = emojiAdapter.getHeight() * 3
//            emojiAdapter.setNewData(urlList)
//            emojiAdapter.onItemClickListener =
//                BaseQuickAdapter.OnItemClickListener { adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int ->
//                    setFace(
//                        requireContext(), editText!!, idList!![position]
//                    )
//                }
//        }
//    }

    override fun onPause() {
        super.onPause()
        if (isMicroLive) {
            EventBus.getDefault().post(NotifyMicroEvent(false))
        }
        if (!isFinishing){
            EventBus.getDefault().post(NotifyMicroEvent(false))
        }
    }

    override fun onResume() {
        super.onResume()
//        if (isMicroLive) {
            EventBus.getDefault().post(NotifyMicroEvent(true))
//        }
    }
}